package com.witframework.web.mvc;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.DataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import com.witframework.util.DateUtil;

public class PropertyDataBinder extends DataBinder{
	/**
	 * Create a new XmlDataBinder instance, with default object name.
	 * @param target target object to bind onto
	 * @see #DEFAULT_OBJECT_NAME
	 */
	public PropertyDataBinder(Object target) {
		super(target);
		init();
	}

	/**
	 * Create a new XmlDataBinder instance.
	 * @param target target object to bind onto
	 * @param objectName objectName of the target object
	 */
	public PropertyDataBinder(Object target, String objectName) {
		super(target, objectName);
		init();
	}
	private void init(){
		SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.getDatePattern());
        dateFormat.setLenient(false);
		registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
        registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
        registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
        registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));
        registerCustomEditor(String.class, null,new StringTrimmerEditor(true));
	}
	public void bind(String propertyName,String value) {
		MutablePropertyValues mpvs = new ParameterPropertyValues(propertyName,value);
		doBind(mpvs);
	}
	@Override
	public boolean isAllowed(String propertyName){
		return super.isAllowed(propertyName);
	}
}
